﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Windows.Storage;

namespace drewCo.Tools
{
  // ============================================================================================================================
  internal sealed class AppDomain
  {
    public static AppDomain CurrentDomain { get; private set; }

    // --------------------------------------------------------------------------------------------------------------------------
    static AppDomain()
    {
      CurrentDomain = new AppDomain();
    }

    // --------------------------------------------------------------------------------------------------------------------------
    public Assembly[] GetAssemblies()
    {
      return GetAssemblyListAsync().Result.ToArray();
    }

    // --------------------------------------------------------------------------------------------------------------------------
    private async Task<List<Assembly>> GetAssemblyListAsync()
    {
      StorageFolder folder = Windows.ApplicationModel.Package.Current.InstalledLocation;

      List<Assembly> assemblies = new List<Assembly>();
      var allFiles = await folder.GetFilesAsync();

      // All of the assemblies in the current location.    
      List<string> asmNames = (from x in allFiles
                               where x.FileType == ".dll" || x.FileType == ".exe"
                               select Path.GetFileNameWithoutExtension(x.Name)).ToList();

      // Some of the usual suspects too....
      // Add to this list as needed.
      asmNames.AddRange(new[]
      { 
        "mscorlib",
        //"System.Runtime.dll",
      });


      foreach (var name in asmNames)
      {
        try
        {
          AssemblyName asmName = new AssemblyName() { Name = name };
          Assembly asm = Assembly.Load(asmName);
          assemblies.Add(asm);
        }
        catch (Exception ex)
        {
          Debug.WriteLine("Could not load the assembly '{0}'", name);
        }
      }

      // Some of the ususal ones too....
      //assemblies.Add(typeof(int).GetTypeInfo().Assembly);


      //foreach (Windows.Storage.StorageFile file in allFiles)
      //{
      //  if (file.FileType == ".dll" || file.FileType == ".exe")
      //  {
      //    string asmName = Path.GetFileNameWithoutExtension(file.Name);
      //  }
      //}

      return assemblies;
    }
  }
}
